<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>文件上传</title>
    <script src="./js/loadsource.js"></script>
  </head>

  <body>
    <div class="card" style="width: 18rem">
      <img class="card-image" src="https://img0.baidu.com/it/u=1705694933,4002952892&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1672506000&t=53ad9a393e8bc0bf66d768b7aacfe974" class="card-img-top" alt="..." />
      <div class="card-body">
        <h5 class="card-title">Card title</h5>
        <p class="card-text">点击按钮，选择图片进行上传</p>
        <a href="javascript:void(0)" class="btn btn-primary upload">点击上传</a>
      </div>
    </div>
    <script>
      (function () {
        const BASE_URL = 'https://sm.ms/api/v2';
        const TOKEN = 'oBQdvvolY4p6Ru4WB4c28x7h8Ykdq2PX';
        const uploadBtn = document.querySelector('.upload');

        uploadBtn.onclick = function () {
          let input = document.createElement('input');
          input.setAttribute('type', 'file');
          input.setAttribute('accept', 'image/*');
          input.setAttribute('multiple', 'multiple');
          input.click();

          input.onchange = function (e) {
            let fileList = [...this.files];
            fileList.forEach(async (file) => {
              console.log(file, '----file');
              let formData = new FormData();
              formData.append('smfile', file);
              formData.append('format', 'json');

              let url = BASE_URL + '/upload';
              let data = await fetch(url, {
                method: 'post',
                headers: {
                  Authorization: `Basic ${TOKEN}`,
                  'Content-Type': 'application/json;charset=UTF-8',
                },
                body: formData,
              }).then((res) => res.json());
            });
          };
        };
      })();
    </script>
  </body>
</html>
